package com.yimo.interceptor;

import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

/**
 * create by jsm on 2018/3/20
 */
@Service
public class CrawlerInterceptor implements HandlerInterceptor {
    private final List<String> allowedOrigins = Arrays.asList("http://localhost:8000", "https://www.yimobuy.com", "http://www.yimobuy.com", "https://www.yimocloud.com", "http://www.yimocloud.com", "https://www.yimoshop.com", "http://www.yimoshop.com", "https://www.yimobiz.com", "http://www.yimobiz.com", "https://www.yimolive.com", "http://www.yimolive.com");
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String origin = httpServletRequest.getHeader("Origin");
        System.out.println("Found " + origin);
        httpServletResponse.setHeader("Access-Control-Allow-Origin", allowedOrigins.contains(origin) ? origin : "");
        httpServletResponse.setHeader("Access-Control-Allow-Headers","Origin, loginToken, X-Requested-With, Content-Type, Accept");
        httpServletResponse.setHeader("Access-Control-Allow-Methods","*");
        httpServletResponse.setHeader("Access-Control-Allow-Credentials","true");
        if (httpServletRequest.getMethod().equals("OPTIONS")) {
            httpServletResponse.setStatus(HttpStatus.NO_CONTENT.value());
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
